package zhaomh.zlogin.Commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import zhaomh.zlogin.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginCommand implements CommandExecutor {
    private static final Map<String,Integer> map = new HashMap<>();
    PlayerTools player;
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player))
            return false;

        player = new PlayerTools((Player) sender);

        if (PlayerData.isPlayerInList(player.getPlayer())) {
            player.sendPluginMessage(Language.get("login.failure.already_has"));
            return true;
        }

        if (args.length != 1){
            player.sendPluginMessage(Language.get("login.correct_formatting"));
            return true;
        }

        List<String> players = Tools.getKeysAtPath(Data.data, "players");
        System.out.println(Arrays.toString(players.toArray()));
        if (players == null || !players.contains(player.getName())) {
            player.sendPluginMessage(Language.get("login.failure.no-exist"));
            return true;
        }

        if (!args[0].equals(Data.data.getString("players."+player.getName()+".password"))) {
            player.sendPluginMessage(Language.get("login.failure.error"));
            int errorCount = map.getOrDefault(player.getName(), 0);
            map.put(player.getName(), errorCount + 1);
            if (map.get(player.getName()) > Data.config.getInt("login.number_errors")) {
                map.put(player.getName(), 0);
                player.getPlayer().kickPlayer(Language.get("login.kick.number_errors").
                        replace("${number_errors}",Data.config.getInt("login.number_errors")+""));
            }

            return true;
        }

        map.put(player.getName(), 0);

        PlayerData.addPlayer(player.getPlayer());
        player.sendPluginMessage(Language.get("login.success"));
        return true;
    }
    public static void removePlayerInMap(String name) {
        map.put(name,0);
    }
}
